package com.xyebank.ledger.service.xjfq.conf;


import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

import javax.sql.DataSource;

@Configuration
// 扫描 Mapper 接口并容器管理
@MapperScan(basePackages = XJFQDataConfig.PACKAGE, sqlSessionFactoryRef = "xjfqSqlSessionFactory")
public class XJFQDataConfig {
    // 精确到 master 目录，以便跟其他数据源隔离
    static final String PACKAGE = "com.xyebank.ledger.service.xjfq.dataProvider";
    static final String MAPPER_LOCATION = "classpath:mapper/xjfq/*.xml";
    @Value("${cw.datasource.url}")
    private String url;

    @Value("${cw.datasource.username}")
    private String user;

    @Value("${cw.datasource.password}")
    private String password;

    @Value("${cw.datasource.driverClassName}")
    private String driverClass;

    @Bean(name = "xjfqDataSource")
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean(name = "xjfqTransactionManager")
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }

    @Bean(name = "xjfqSqlSessionFactory")
    public SqlSessionFactory clusterSqlSessionFactory(@Qualifier("xjfqDataSource") DataSource master2DataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(master2DataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(XJFQDataConfig.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }

    @Bean(name="xjfqTransactionTemplate")
    public TransactionTemplate transactionTemplate() {
        TransactionTemplate transactionTemplate = new TransactionTemplate();
        transactionTemplate.setTransactionManager(transactionManager());
        transactionTemplate.setPropagationBehaviorName("PROPAGATION_REQUIRES_NEW");
        return transactionTemplate;
    }
}
